package com.huashi.dealer.modular.business.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huashi.dealer.commonEntity.Category;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.category.mapper.GiftCategoryMapper;
import com.huashi.dealer.modular.business.category.param.GiftCategorySaveParam;
import com.huashi.dealer.modular.business.category.service.GiftCategoryService;
import com.huashi.dealer.modular.business.category.vo.GiftCategoryVo;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.goods.vo.GoodsImageWithUrl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GiftCategoryServiceImpl implements GiftCategoryService {

    @Resource
    private GiftCategoryMapper categoryMapper;

    @Resource
    private GoodsImageMapper goodsImageMapper;

    @Override
    public List<GiftCategoryVo> getGiftCategoryTree() {
        // 查询所有赠品分类（is_type = 20）
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getIsType, 20)
                .orderByAsc(Category::getSort)
                .orderByAsc(Category::getCreateTime);

        List<Category> allCategories = categoryMapper.selectList(queryWrapper);
        
        if (CollectionUtils.isEmpty(allCategories)) {
            return new ArrayList<>();
        }

        // 转换为VO
        List<GiftCategoryVo> allCategoryVos = allCategories.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());

        // 构建树形结构
        return buildTree(allCategoryVos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateCategory(GiftCategorySaveParam param) {
        Category category = new Category();
        category.setCategoryId(param.getCategoryId());
        category.setName(param.getName());
        category.setParentId(param.getParentId());
        category.setImageId(param.getImageId());
        category.setSort(param.getSort());
        category.setIsType(param.getIsType()); // 固定为赠品分类
        category.setIsGoodsType(param.getIsGoodsType());
        category.setCreateTime(System.currentTimeMillis() / 1000);

        if (param.getCategoryId() == null) {
            // 新增
            categoryMapper.insert(category);
        } else {
            // 编辑
            category.setUpdateTime(System.currentTimeMillis() / 1000);
            categoryMapper.updateById(category);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategory(Long categoryId) {
        // 检查是否有子分类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, categoryId);
        
        long childCount = categoryMapper.selectCount(queryWrapper);
        if (childCount > 0) {
            throw new RuntimeException("该分类下还有子分类，无法删除");
        }

        // 硬删除
        categoryMapper.deleteById(categoryId);
    }

    @Override
    public GiftCategoryVo getCategoryDetail(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            return null;
        }
        return convertToVo(category);
    }

    /**
     * 转换为VO
     */
    private GiftCategoryVo convertToVo(Category category) {
        GiftCategoryVo vo = new GiftCategoryVo();
        vo.setCategoryId(category.getCategoryId());
        vo.setName(category.getName());
        vo.setParentId(category.getParentId());
        vo.setImageId(category.getImageId());
        vo.setSort(category.getSort());
        vo.setIsType(category.getIsType());
        vo.setIsGoodsType(category.getIsGoodsType());
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(category.getCreateTime()));
        vo.setUpdateTime(TimeUtil.changeToLocalDateTime(category.getUpdateTime()));
        // 获取图片URL
        if (category.getImageId() != null) {
            List<GoodsImageWithUrl> imageInfos = goodsImageMapper.getGoodsImageWithUrl(category.getImageId());
            if (!CollectionUtils.isEmpty(imageInfos)) {
                vo.setImageUrl(imageInfos.get(0).getFileUrl());
            }
        }

        return vo;
    }

    /**
     * 构建树形结构
     */
    private List<GiftCategoryVo> buildTree(List<GiftCategoryVo> allCategories) {
        // 按父ID分组
        Map<Long, List<GiftCategoryVo>> parentMap = allCategories.stream()
                .collect(Collectors.groupingBy(category -> 
                    category.getParentId() == null ? 0L : category.getParentId()));

        // 递归设置子分类
        allCategories.forEach(category -> {
            List<GiftCategoryVo> children = parentMap.get(category.getCategoryId());
            if (children != null) {
                category.setChildren(children);
            }
        });

        // 返回顶级分类
        return parentMap.get(0L) != null ? parentMap.get(0L) : new ArrayList<>();
    }
}
